package com.blindBox.back.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils
{
    @Autowired
    private RedisTemplate redisTemplate;

    //绑定key,并设置过期时间
    public void boundKey(String key, String value, Integer time,TimeUnit size)
    {
        redisTemplate.boundValueOps(key).set(value,time,size);
    }

    //绑定key,不设置过期时间
    public void boundKey(String key, String value)
    {
        redisTemplate.boundValueOps(key).set(value);
    }

    //删除key
    public void delete(String key){
        redisTemplate.delete(key);
    }

    //删除多个key
    public void deleteKey (String ...keys){
        redisTemplate.delete(keys);
    }

    //指定key的失效时间
    public void expire(String key,long time){
        redisTemplate.expire(key,time, TimeUnit.MINUTES);
    }

    //根据key获取过期时间
    public long getExpire(String key){
        Long expire = redisTemplate.getExpire(key);
        return expire;
    }

    //判断key是否存在
    public boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }

     //哈希相关的操作

    //填入一条数据，并设置过期时间
    public void putIntoHash(String ID,String key, String value, Integer time,TimeUnit size)
    {
        redisTemplate.boundHashOps(ID).put(key, value);
        redisTemplate.expire(ID,time,size);
    }

    //填入一条数据，不设置过期时间
    public void putIntoHash(String ID,String key, String value)
    {
        redisTemplate.boundHashOps(ID).put(key, value);
    }

    //获取所有key值
    public Set getAllKeys(String ID)
    {
        Set keys = redisTemplate.boundHashOps(ID).keys();
        return keys;
    }

    //获取所有value值
    public List getAllValues(String ID)
    {
        List values = redisTemplate.boundHashOps(ID).values();
        return values;
    }

    //根据key获取value值
    public String getValueByKey(String ID,String key)
    {
        String value = (String) redisTemplate.boundHashOps(ID).get(key);
        return value;
    }

    //删除大key
    public void delBigKey(String ID)
    {
        redisTemplate.delete(ID);
    }

    //删除小key
    public void delSmallKey(String ID,String key)
    {
        //删除小key
        redisTemplate.boundHashOps(ID).delete(key);
    }

    //判断是否存在key
    public Boolean hashHasKey(String ID,String key)
    {
       return redisTemplate.boundHashOps(ID).hasKey(key);
    }

}
